import React, { useEffect, useState } from 'react';
import { Table, Space, Button, message, Modal, Form, Input, Popconfirm, TreeSelect } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { DataNode } from 'antd/es/tree';
import { RoleItem, PermissionItem } from 'admin/schema/Cas';
import {
  getCasRoles,
  addCasRole,
  updateCasRole,
  deleteCasRole,
  getCasPermissionTree,
  getCasRolePermissions,
} from 'admin/servers/modules/Cas';
import { debounce, filter, map } from 'lodash';

interface FormValues {
  name: string;
  description: string;
  permissions: string[];
}

const Roles: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<RoleItem[]>([]);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [modalTitle, setModalTitle] = useState<string>('新增角色');
  const [form] = Form.useForm<FormValues>();
  const [editingId, setEditingId] = useState<string | null>(null);
  const [permissionTree, setPermissionTree] = useState<DataNode[]>([]);
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);

  // 获取角色列表
  const fetchRoles = async () => {
    setLoading(true);
    try {
      const response = await getCasRoles();
      if (response.status === 200) {
        setData(response.data);
      }
    } catch (error) {
      console.error('获取角色列表出错:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取权限树
  const fetchPermissionTree = async () => {
    try {
      const response = await getCasPermissionTree();
      if (response.status === 200) {
        const transformToTreeData = (items: PermissionItem[]): DataNode[] => {
          return items.map(item => ({
            title: item.name,
            value: item.id,
            key: item.id,
            children: item.children ? transformToTreeData(item.children) : undefined,
          }));
        };
        setPermissionTree(transformToTreeData(response.data));
      }
    } catch (error) {
      console.error('获取权限树出错:', error);
    }
  };

  // 获取角色权限
  const fetchRolePermissions = async (roleId: string) => {
    try {
      const response = await getCasRolePermissions(roleId);
      if (response.status === 200) {
        const permissionIds = filter(response.data, item => item.pid !== '0').map(item => item.id);
        setSelectedPermissions(permissionIds);
        form.setFieldsValue({ permissions: permissionIds });
      }
    } catch (error) {
      console.error('获取角色权限出错:', error);
    }
  };

  useEffect(() => {
    fetchRoles();
    fetchPermissionTree();
  }, []);

  const handleAdd = () => {
    setModalTitle('新增角色');
    setEditingId(null);
    setSelectedPermissions([]);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = async (record: RoleItem) => {
    setModalTitle('编辑角色');
    setEditingId(record.id);
    form.setFieldsValue({
      name: record.name,
      description: record.description || '',
    });
    await fetchRolePermissions(record.id);
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      const response = await deleteCasRole({ id });
      if (response.status === 200) {
        message.success('删除成功');
        fetchRoles();
      }
    } catch (error) {
      console.error('删除出错:', error);
    }
  };

  const handleModalOk = debounce(async () => {
    try {
      const values = await form.validateFields();

      if (editingId) {
        // 更新
        const response = await updateCasRole({
          id: editingId,
          name: values.name,
          description: values.description,
          permissions: values.permissions,
        });

        if (response.status === 200) {
          message.success('更新成功');
          setModalVisible(false);
          fetchRoles();
        }
      } else {
        // 新增
        const response = await addCasRole({
          name: values.name,
          description: values.description,
          permissions: values.permissions,
        });

        if (response.status === 200) {
          message.success('添加成功');
          setModalVisible(false);
          fetchRoles();
        }
      }
    } catch (error) {
      console.error('表单验证或提交出错:', error);
    }
  }, 500);

  const handleModalCancel = () => {
    setModalVisible(false);
  };

  const handlePermissionChange = (value: string[]) => {
    setSelectedPermissions(value);
  };

  const columns: ColumnsType<RoleItem> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      render: text => text || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      render: time => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此角色吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px' }}>
        <Button type="primary" onClick={handleAdd}>
          新增角色
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        maskClosable={false}
        destroyOnClose
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="名称"
            rules={[
              { required: true, message: '请输入名称' },
              { max: 60, message: '最大长度为60位字符' },
            ]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={[{ max: 255, message: '最大长度为255位字符' }]}
          >
            <Input.TextArea placeholder="请输入描述" />
          </Form.Item>

          <Form.Item
            name="permissions"
            label="权限"
            rules={[{ required: true, message: '请选择权限' }]}
          >
            <TreeSelect
              treeData={permissionTree}
              treeCheckable
              showCheckedStrategy={TreeSelect.SHOW_ALL}
              placeholder="请选择权限"
              style={{ width: '100%' }}
              value={selectedPermissions}
              onChange={handlePermissionChange}
              maxTagCount={3}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Roles;
